﻿using CRM.Infrastructure.Dto.Request.order;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.Tools;
using CRM.Service.Interface;  
 
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Web;
using XSystem.Security.Cryptography;

namespace CRM.Api.Admin.Controllers
{
    public class OrderController : BaseController
    {

        private readonly I_Order_Service _order_Service;

        public OrderController(I_Order_Service order_Service, I_Login_Service login_Service) : base(login_Service)
        {
            _order_Service = order_Service;

        }


        private long Get_Timer()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

        public class SamplesResult
        {
            public string Openid { get; set; }

            public string Url { get; set; }

            public string Errcode { get; set; }

            public string Errmsg { get; set; }

            public string Hash { get; set; }
        }

        /// <summary>
        /// 订单支付完成后的通知地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NotifyUrl([FromForm] string trade_order_id,
            [FromForm] string total_fee,
            [FromForm] string transaction_id,
            [FromForm] string plugins,
            [FromForm] string status,
            [FromForm] string hash)
        {



            string path = $"/www/logs/crm/{DateTime.Now.ToString("yyyyMMdd")}.txt";
            System.IO.File.AppendAllText(path, $"时间：{DateTime.Now}\r\n" +
                $"tradeOrderId={trade_order_id}\r\n" +
                $"totalFee={total_fee}\r\n" +
                $"transactionId={transaction_id}\r\n" +
                $"plugins={plugins}\r\n" +
                $"status={status}\r\n" +
                $"hash={hash}\r\n");

            Api_Response_Dto result = _order_Service.Finish_Pay(trade_order_id, total_fee);


            return Content("success");
        }

        private static string PostHttp(Dictionary<string, string> dicArray)
        {
            string result;

            try
            {
                var req = (HttpWebRequest)WebRequest.Create("https://api.xunhupay.com/payment/do.html");
                req.KeepAlive = false;
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Accept = "application/json";

                var paramData = ParamData(dicArray);
                var data = Encoding.Default.GetBytes(paramData);

                req.ContentLength = data.Length;

                var swrite = req.GetRequestStream();
                swrite.Write(data, 0, data.Length);
                swrite.Close();

                var resp = (HttpWebResponse)req.GetResponse();
                var stream = resp.GetResponseStream();

                //获取响应内容
                var reader = new StreamReader(stream ?? throw new InvalidOperationException(), Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                result = ex.Message;
            }

            return result;
        }

        private static string Sign(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray.OrderBy(o => o.Key))
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
            var signValue = Md5Encoder(prestr + "4d073f520cc2e723ee13a5227bf1bd27", 32);
            return signValue;
        }

        private static string ParamData(Dictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        private static string Md5Encoder(string str, int bit)
        {
            var md5Hasher = new MD5CryptoServiceProvider();
            var hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(str));
            var tmp = new StringBuilder();
            foreach (var i in hashedDataBytes)
            {
                tmp.Append(i.ToString("x2"));
            }

            switch (bit)
            {
                case 16:
                    return tmp.ToString().Substring(8, 16);
                case 32:
                    return tmp.ToString();//默认情况
            }

            return string.Empty;
        }

        /// <summary>
        /// 生成支付订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Generate_Pay(Pay_Rerquest_Dto dto)
        {

            if (dto.money <= 0)
            {
                return BadRequest("参数错误");
            }

            var json = new JObject();

            string pid = RandomNumber.GeneraOrderNumber3();

            try
            {
                var dic = new Dictionary<string, string>
                    {
                        {"version", "1.1"},
                        {"lang", "zh-cn"},
                        {"plugins", "test-001"},
                        {"appid", "201906136505"},//appid
	                    {"appsecret", "4d073f520cc2e723ee13a5227bf1bd27 "},//appsecret
	                    {"trade_order_id", pid},//订单号
	                    {"payment", "wechat"},//支付类型
	                    {"total_fee", dto.money.ToString()},//金额
	                    {"title", HttpUtility.UrlEncode("iphone")},//标题，中文需要编码“HttpUtility.UrlEncode()”
	                    {"time", Get_Timer().ToString()},//时间戳
	                    {"notify_url", "http://43.139.80.8/api/Order/NotifyUrl"},//通知链接
	                    {"return_url", "https://www.doubao.com/"},//跳转链接
	                    {"nonce_str", Guid.NewGuid().ToString()},//随机字符串
	                };

                dic.Add("hash", Sign(dic));

                var sr = JsonConvert.DeserializeObject<SamplesResult>(PostHttp(dic));

                json.Add(new JProperty("openid", sr.Openid));
                json.Add(new JProperty("url", sr.Url));
                json.Add(new JProperty("errcode", sr.Errcode));
                json.Add(new JProperty("errmsg", sr.Errmsg));
                json.Add(new JProperty("hash", sr.Hash));

                //生成一个待支付的订单
                if (sr.Errcode == "0")
                {
                    Api_Response_Dto result = await _order_Service.Generate_Pay(pid, dto.oid, dto.money);
                    result.data = sr.Url;
                    return Ok(result);
                    //成功
                }
                return Ok(new Api_Response_Dto
                {
                    code = (Api_Code)Convert.ToInt32(sr.Errcode),
                    message = sr.Errmsg,
                    data = sr.Url,
                });
            }
            catch (Exception e)
            {
                throw e;
            }
        }


        /// <summary>
        /// 创建订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Generate_Order(Order_Request_Dto dto)
        {
            Api_Response_Dto result = await _order_Service.Generate_Order(dto);
            return Ok(result);
        }

        /// <summary>
        /// 根据房间号获取订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get_Order_By_Room(string id)
        {
            Api_Response_Dto result = await _order_Service.Get_Order_By_Room(id);
            return Ok(result);
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update_Order(Order_Request_Dto dto)
        {
            Api_Response_Dto result = await _order_Service.Update_Order(dto);
            return Ok(result);
        }
        /// <summary>
        /// 获取所有房间
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get_Room()
        {
            Api_Response_Dto result = await _order_Service.Get_Room();
            return Ok(result);
        }
        /// <summary>
        /// 获取所有订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get_Order()
        {
            Api_Response_Dto result = await _order_Service.Get_Order();
            return Ok(result);
        }
        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get_Order_details(string id)
        {
            Api_Response_Dto result = await _order_Service.Get_Order_details(id);
            return Ok(result);
        }
    }
}
